import React, { useEffect, useMemo, useState } from "react"
import { Table as AntdTable} from "antd"
import { CommonComponenetProps } from "../../interface"
import dayJs from "dayjs"
import axios from "axios"

const Table = ({ url, children }: CommonComponenetProps) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState([])

    const getData = async() => {
        if (url) {
            setLoading(true)

            let { data } = await axios.get(url)

            setData(data)

            setLoading(false)
        }
    }

    useEffect(() => {
        getData()
    }, [url])

    const columns = useMemo(() => {
        // React.Children 是 React 提供的一个工具集合，用于处理 this.props.children 中的 React 子元素。
        // 下面是规定数据渲染格式
        return React.Children.map(children, (item: any) => {
            if(item?.props?.type === 'date') {
                return {
                    title: item.props?.title,
                    dataIndex: item.props?.dataIndex,
                    render: (value: any) => value ? dayJs(value).format('YYYY-MM-DD') : null,
                }
            } else {
                return {
                    title: item.props?.title,
                    dataIndex: item.props?.dataIndex,
                }
            }
        })
    }, [children])

    return (
        <AntdTable 
            columns={columns}
            dataSource={data}
            pagination={false}
            rowKey="key"
            loading={loading}
        />
    )
}

export default Table